from apps.pay.lzpay.baseViews import *
from apps.interface.client.models import Client
from apps.pay.order.dao import OrderDao
from apps.common.utils.time import getFormatTime
from apps.pay.recordIncomes.dao import RecordIncomesDao
from project.config import env

class LzPayViewSet(BaseLzpayViewSet):
    
    ''''单笔代付'''
    @action(methods=['post'], detail=False)
    def paymentSingle(self, request):
        params = getRequestParams(request)
        if not params.get('obj_id'):
            return Response(response_message('obj_id参数必填'))
        recordIncome = RecordIncomesDao().findOneByObjId(params.get('obj_id'))
        if not recordIncome.orderId:
            return Response(response_message('订单号不能为空'))
        if recordIncome.orderStatus != 'WAIT_SEND':
            return Response(response_message("待打款的订单才允许处理！"))
        if not recordIncome.receiptAccount:
            return response_message('收款账户不能为空')
        receiptAccount = json.loads(recordIncome.receiptAccount)
        remark = recordIncome.remark
        merOrderNo = recordIncome.orderId
        accountName = receiptAccount.get('creditedName')
        cardNo = receiptAccount.get('creditedAccount')
        bankNo = receiptAccount.get('bankCode')
        tradeAmount = recordIncome.realMoney

        r_params =  {
            "signType": self.signType,
            "signSN": self.signSN,
            "encryptSN": self.encryptSN,
            "merchantNo": self.merchantNo
        }

        cardType = "00" # 卡类型
        currency = "CNY"

        r_params.update({
            "tradeType": "SINGLE",
            "payType": "PAY_FOR_ANOTHER",
            "merOrderNo": merOrderNo,
            "tradeTime": datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
            "cardType": cardType,
            "tradeAmount": tradeAmount,
            "currency": currency,
            "bankNo": bankNo,
            "remark": remark,
            "notifyUrl": "https://xlmp.service.qly.plus" + "/api/pay/lzpay/pay/paymentback/",
        })
        # 加密身份证和手机号
        encrypt_data = self.encrypt(accountName, cardNo)
        accountName = encrypt_data.get('data1')
        cardNo = encrypt_data.get('data2')
        r_params["accountName"] = encrypt_data.get('data1')
        r_params["cardNo"] = encrypt_data.get('data2')
        r_params["digitalEnvelope"] = encrypt_data.get('digitalEnvelope')

        sign = self.getSign(r_params)
        if sign:
            r_params['sign'] = sign
        else:
            return Response(response_message('获取签名失败'))
        # 输出程序输出
        url = "https://pay.lzpay.com/api/payment/paymentSingle"
        headers = {'content-type': "application/x-www-form-urlencoded;charset=UTF-8"}
        print('r_params', r_params)
        if env != 'prod':
            return Response(response_message('测试环境不支持此功能'))
        res = requests.post(url, data=r_params, headers=headers)
        res_content = json.loads(res.content)
        print('res_content', res_content)
        if res_content.get('code') == '00':
            return Response(response_message(res_content.get('message')))
        else:
            return Response(response_message(res_content.get('message')))
    

    ''''批量代付'''
    @action(methods=['post'], detail=False)
    def paymentBatch(self, request):
        params = getRequestParams(request, False)
        obj_id = params.get('obj_id')
        if not obj_id:
            return Response(response_message('obj_id参数必填'))

        r_params =  {
            "signType": self.signType,
            "signSN": self.signSN,
            "encryptSN": self.encryptSN,
            "merchantNo": self.merchantNo
        }

        accountType = "00" # 卡类型
        currency = "CNY"
        accountName = "平安银行股份有限公司"
        bankNo = "1011"
        cardNo = "6230580000092698815"
        bankBranch = "支行"
        remark = params.get('remark')
        totalNumber = "1" # 交易数量
        tradeAmount = "0.01" # 交易金额

        r_params.update({
            "tradeType": "BATCH",
            "payType": "PAY_FOR_ANOTHER",
            "merBatchNo": getFormatTime('%Y%m%d%H%M%S') + random_num(8),
            "tradeTime": datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
            "totalNumber": totalNumber,
            "totalAmount": tradeAmount,
            "notifyUrl": "https://xlmp.service.qly.plus" + "/api/pay/lzpay/pay/paymentback/",
        })
        # 加密身份证和手机号
        encrypt_data = self.encrypt(accountName, cardNo)
        accountName = encrypt_data.get('data1')
        cardNo = encrypt_data.get('data2')
        r_params["digitalEnvelope"] = encrypt_data.get('digitalEnvelope')
        # 收款账户订单信息
        paymentData = []
        paymentData.append(params.get('orderId'))
        paymentData.append(accountName)
        paymentData.append(cardNo)
        paymentData.append(accountType)
        paymentData.append(tradeAmount)
        paymentData.append(currency)
        paymentData.append(bankNo)
        paymentData.append(bankBranch)
        paymentData.append(remark)
        print('paymentData', paymentData)

        r_params["paymentData"] = '|'.join(paymentData)
        sign = self.getSign(r_params)
        if sign:
            r_params['sign'] = sign
        else:
            return Response(response_message('获取签名失败'))
        # 输出程序输出
        url = "https://pay.lzpay.com/api/payment/paymentBatch"
        headers = {'content-type': "application/x-www-form-urlencoded;charset=UTF-8"}
        print('r_params', r_params)
        res = requests.post(url, data=r_params, headers=headers)
        res_content = json.loads(res.content)
        print('res_content', res_content)
        if res_content.get('code') == '00':
            return Response(response_message(res_content.get('message')))
        else:
            return Response(response_message(res_content.get('message')))
    
    '''代付异步回调'''
    @action(methods=['post'], detail=False, authentication_classes=[],permission_classes=[])
    def paymentback(self, request):
        try:
            body = request.body
            body_str = body.decode('utf-8')
            # 分割成键值对
            pairs = body_str.split('&')
            # 解析键值对
            order_dict = {}
            for pair in pairs:
                key, value = pair.split('=')
                order_dict[key] = value
            # 输出解析后的字典
            print('order_dict', order_dict)
            print('merOrderNo', order_dict.get('merOrderNo'))
            print('orderNo', order_dict.get('orderNo'))
            _out_trade_no = order_dict.get('merOrderNo')
            orderNo = order_dict.get('orderNo')
            # 处理业务订单
            
            recordIncome = RecordIncomesDao().findAll().filter(orderId=_out_trade_no).first()
            if recordIncome.orderStatus == 'WAIT_SEND':
                RecordIncomesDao().update(recordIncome.id, {'orderStatus': 'FINISH', 'outMoneyTime': datetime.datetime.now()})
            res_str = "SUCCESS"
            res_bytes = res_str.encode('utf-8')
            return Response(res_bytes)
        except Exception as e:
            print('代付回调异常', e)
            res_str = "FAIL"
            res_bytes = res_str.encode('utf-8')
            return Response(res_bytes)